<script setup>
import { ref ,h, watch } from 'vue'
import { VueFlow, useVueFlow } from '@vue-flow/core'
import { Background } from '@vue-flow/background'
import { ControlButton, Controls } from '@vue-flow/controls'
import { MiniMap } from '@vue-flow/minimap'
import Icon from './Icon.vue'
import { useDialog } from 'naive-ui'

import AiNode from './AiTaskNode.vue'
import FileNode from './FileNode.vue'
import NetworkNode from './NetworkNode.vue'
import ChatNode from './ChatNode.vue'
import Sidebar from './Sidebar.vue'

import useDragAndDrop from './useDragAdd'


const { onDragOver, onDrop, onDragLeave, isDragOver, onDropCallback } = useDragAndDrop()

console.log("session in task")
const dialog = useDialog()

const menuContext = ref({
    show: false,
    optionsComponent: {
      zIndex: 3,
      minWidth: 230,
      x: 500,
      y: 200
    }
  })

const { onInit,onNodeDragStop,applyNodeChanges,onPaneClick,onPaneContextMenu, applyEdgeChanges,onNodesChange, onEdgesChange, onConnect, addEdges, setViewport, toObject } = useVueFlow()
onConnect((params) => {
  addEdges(params)
})



const addNode = ref({
    show:false,
    type: 'llm',
})
const labels = ref([
    { label: "AI prompt node", value: 'prompt' },
])
const nodes = defineModel("nodes",{
  default:[]
})

// watch(()=>nodes.value,(newVal)=>{
//   nodes.value = newVal
// },{deep:true})
// setInterval(()=>{
//   console.log(nodes.value)
//   console.log(nodes.value)
// },10000)

const edges = ref([
])

const dark = ref(true)

onInit((vueFlowInstance) => {
  vueFlowInstance.fitView()
})



onNodesChange(async (changes) => {
  const nextChanges = []

  for (const change of changes) {
    if (change.type === 'remove') {
      // console.log('removing node', change.id)
      // removeNode change.id
      nodes.value = nodes.value.filter((node) => node.id !== change.id)

      
    } else {
      nextChanges.push(change)
    }
  }
  
})

onEdgesChange(async (changes) => {
  const nextChanges = []

  for (const change of changes) {
    if (change.type === 'remove') {
      // remove edege
      edges.value = edges.value.filter((edge) => edge.id !== change.id)
    } else {
      nextChanges.push(change)
    }
  }

  applyEdgeChanges(nextChanges)
})

const addNewNode  = (type) =>{
  let p ={
      x: menuContext.value.optionsComponent.x-100,
      y: menuContext.value.optionsComponent.y-200,
    };

  // console.log("gen :",p)
  let id = Math.random().toString(36);
  nodes.value.push({
    id: id,
    type,
    position: p,
  })
}

onDropCallback((nodeInfo)=>{
  // console.log("drop:",nodeInfo)
  nodes.value.push(nodeInfo)
})

/**
 * Resets the current viewport transformation (zoom & pan)
 */
function resetTransform() {
  setViewport({ x: 0, y: 0, zoom: 1 })
}

function toggleDarkMode() {
  dark.value = !dark.value
}

const onContextMenu = (e ) =>{
    //Show component mode menu
    // console.log("Gear",e)
    
    menuContext.value.optionsComponent.x = e.x;
    menuContext.value.optionsComponent.y = e.y;
    menuContext.value.show = true;
}    
// onPaneClick((event) => {
//   console.log('pane click', event)
// })
onPaneContextMenu((event) =>{
  console.log('pane ctx menu', event)
  onContextMenu(event)
})

const nodeTypes = [
  "aitask","file", "network","chat"
]
const showChooseNode = ref(true);

</script>

<template>

  <div 
    style="height: 100vh; width: 100vw"
    @drop="onDrop"
  >
  <n-popover trigger="hover" >
    <template #trigger>
      <n-button  strong secondary type="info" style="z-index: 10000; position: fixed; top:10px; left:20vw;width:200px">选择节点</n-button>
    </template>
    <Sidebar v-model:nodes="nodeTypes" />
    
  </n-popover>
  

  <VueFlow
    v-model:nodes="nodes"
    :edges="edges"
    :class="{dark}"
    class="basic-flow"
    @dragover="onDragOver" @dragleave="onDragLeave"
    :min-zoom="0.2"
    :max-zoom="4"
    >
    <Background pattern-color="#fff"  :gap="16"  />
    <template #node-aitask="props">
      <AiNode :id="props.id" :data="props.data" />
    </template>
    <template #node-file="props">
      <FileNode :id="props.id" :data="props.data" />
    </template>
    <template #node-network="props">
      <NetworkNode  :id="props.id" :data="props.data" />
    </template>
    <template #node-chat="props">
      <ChatNode :id="props.id" ></ChatNode>
    </template>
    <MiniMap />

    <Controls position="top-left">
      <ControlButton title="Reset Transform" @click="resetTransform">
        <Icon name="reset" />
      </ControlButton>

    </Controls>
  </VueFlow>
  <context-menu
    v-model:show="menuContext.show"
    :options="menuContext.optionsComponent"
  >
    <!-- <context-menu-item label="增加节点" @click="onMenuClick(1)" /> -->
    <context-menu-sperator /><!--use this to add sperator-->
    <context-menu-group label="增加节点">
      <context-menu-item label="文件节点" @click="addNewNode('file')" />
      <context-menu-item label="AI节点" @click="addNewNode('ai')" />
      <context-menu-item label="网络节点" @click="addNewNode('network')" />
      
    </context-menu-group>
  </context-menu>

  <n-modal v-model:show="addNode.show">
    <n-card
      style="width: 600px"
      title="Modal"
      :bordered="false"
      size="huge"
      role="dialog"
      aria-modal="true"
    >
      
      Content
      <template #footer>
        Footer
      </template>
    </n-card>
  </n-modal>

  
  </div>
</template>

<style>
.basic-flow.dark{
  /* background: #191919; */
}
</style>